// pages/goods_detail/index.js
// 点击加入购物车
  //  1 购物车存储的数据格式，存储在本地存储中
  // {
  //   // 华为商品id： 华为商品信息
  //   // 小米商品id： 小米商品信息
  // }
// 2.先获取本地存储中的购物车对象
    // 先获取本地存储中的购物车对象 || {}
    // 3.给购物车对象添加新属性和值，【】的方式添加
import {
  request
} from '../../request/index';
import regeneratorRuntime from '../../lib/runtime/runtime.js';
import {getStorageCart,setStorageCart} from '../../utils/storage.js'
//Page Object
Page({
  data: {
       goodsInfo: {
        goods_name:'',
        goods_price: '',
        pics: [],
        goods_introduce: '',
       }
  },
  // 定义一个全局的商品对象
  GoodsObj: {},
  //options(Object)
  onLoad: function(options) {
     const {goods_id} = options;
     this.getGoodsDetail(goods_id);
  },
async getGoodsDetail (id){
  const result = await request({url:'/goods/detail?goods_id='+id});
  this.GoodsObj = result;
  // console.log(result)
  this.setData({
    goodsInfo: {
      goods_name: result.goods_name,
      goods_price: result.goods_price,
      pics: result.pics,
      goods_introduce: result.goods_introduce.replace(/\.webp/g,'.jpg'),
     }
  });
},
// 点击轮播图实现放大
handlePreviewImage(e){
  const {index} = e.currentTarget.dataset;
  const urls = this.data.goodsInfo.pics.map(v => v.pics_big);
  const current = urls[index];
  console.log(e)
wx.previewImage({
  current,
  urls
  
});
},
// 加入购物车
handleCateAdd(){
  // console.log(this.GoodsObj.goods_id)
  // 1.获取本地存储中购物车的对象
  // let cart = wx.getStorageSync("cart") || {};
   let cart = getStorageCart() || {};
  // 2.判断商品是佛购买
  if(cart[this.GoodsObj.goods_id]){
          // 2.1已有数据
          cart[this.GoodsObj.goods_id].num++;
  }else{
      //  2.2第一次添加
      cart[this.GoodsObj.goods_id]=this.GoodsObj;
      cart[this.GoodsObj.goods_id].num=1;
      cart[this.GoodsObj.goods_id].checked=true;
  };
  // 3.把数据存储在本地
  // wx.setStorageSync("cart",cart);
  setStorageCart(cart);
  // 4.提示
  wx.showToast({
    title: '加入成功',
    icon: 'success',
    mask: true,
  });
    
    
}

});
  